import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useThemeStore = defineStore('theme', () => {
  const isDark = ref(false)
  const isSystem = ref(true)

  // 初始化主题
  const initTheme = () => {
    const savedTheme = localStorage.getItem('theme')
    const savedSystem = localStorage.getItem('theme-system')
    
    if (savedSystem === 'false') {
      isSystem.value = false
      isDark.value = savedTheme === 'dark'
    } else {
      isSystem.value = true
      isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches
    }
    
    applyTheme()
  }

  // 切换主题
  const toggleTheme = () => {
    isDark.value = !isDark.value
    isSystem.value = false
    applyTheme()
    saveTheme()
  }

  // 设置主题
  const setTheme = (theme) => {
    isDark.value = theme === 'dark'
    isSystem.value = false
    applyTheme()
    saveTheme()
  }

  // 使用系统主题
  const useSystemTheme = () => {
    isSystem.value = true
    isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches
    applyTheme()
    saveTheme()
  }

  // 应用主题到DOM
  const applyTheme = () => {
    const html = document.documentElement
    if (isDark.value) {
      html.classList.add('dark')
      html.setAttribute('data-theme', 'dark')
    } else {
      html.classList.remove('dark')
      html.setAttribute('data-theme', 'light')
    }
  }

  // 保存主题设置
  const saveTheme = () => {
    localStorage.setItem('theme', isDark.value ? 'dark' : 'light')
    localStorage.setItem('theme-system', isSystem.value.toString())
  }

  // 监听系统主题变化
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.addEventListener('change', (e) => {
    if (isSystem.value) {
      isDark.value = e.matches
      applyTheme()
    }
  })

  // 监听主题变化
  watch(isDark, () => {
    applyTheme()
  })

  return {
    isDark,
    isSystem,
    initTheme,
    toggleTheme,
    setTheme,
    useSystemTheme
  }
}) 